import { MTreeNode, modelService, MetaclassType, StType, locale, CanLoadMethods, modelTreeSelectWindow, modelDetail, treeForEach, rmi } from "@/mdesign-lib/mdesign-app.umd.js";
import { RuleManagerWindow } from "../ruleManager";

export interface ValidationModelInstanceVo {
  instanceId: string;
  instanceName: string;
  type: number;
  children: ValidationModelInstanceVo[];
  icon: string;
  isInteractive: boolean;
  qualifiedName: string;
  isEdit?: boolean;
}

export interface ValidationRuleModelVo {
  instanceId: string;
  instanceName: string;
  icon: string;
  children: ValidationRuleModelVo[];
  appliedStereotypes: string[];
  isInteractive: boolean;
  metaClass: string;
  qualifiedName: string;
  ownerId: string;
}

export class ValidateGroupModel {
  groupList: ValidationModelInstanceVo[] = [];
  selectedNode: ValidationRuleModelVo | null = null;
  selectedGroup: ValidationModelInstanceVo | null = null;
  treeNodeMap = new Map<string, MTreeNode>();
  treeData: ValidationRuleModelVo[] = [];
  editingName = "";
  expandedKeys: string[] = [];
  ownerId = "";

  constructor(public projectId: string) {}
  async init() {
    const res = await modelService.queryValidationGroups(this.projectId);
    this.groupList = res.map(item => ({
      ...item,
      icon: modelService.getModelIcon(this.projectId, item.icon),
      isEdit: false
    }));
    if (this.selectedGroup) {
      this.handleClickGroup(this.selectedGroup);
    } else {
      if (this.groupList.length > 0) {
        this.selectedGroup = this.groupList[0];
        this.handleClickGroup(this.groupList[0]);
      } else {
        this.selectedGroup = null;
      }
    }
  }
  async handleClickAdd(str: string) {
    const response = await modelTreeSelectWindow.popup({
      attrTip: "radioSaveAsRule",
      title: "选择所有者",
      delay: false,
      showNodeLabel: true,
      disableReadonlyNode: true,
      projectId: this.projectId,
      loadMethod: CanLoadMethods.getPropertyTreeList,
      loadParams: JSON.stringify({
        row: {
          checkMethod: "validValidationModelElementOwner",
          instanceId: "",
          key: "",
          moreBtnCondition: StType[str]
        },
        projectId: this.projectId
      })
    });
    if (response.success) {
      this.ownerId = response.selectedId as string;
      modelTreeSelectWindow.done();
      const model = await rmi.invoke("app.modelService.addModel", [this.projectId, this.ownerId, MetaclassType.Package, [StType[str]]]);
      if (model) {
        this.init();
      }
    }
  }
  async handleRemoveGroup() {
    if (!this.selectedGroup?.isInteractive) {
      return;
    }
    if (!this.selectedGroup) {
      return app.$notify({
        title: "提示",
        type: "info",
        message: "请选择要删除的分组"
      });
    }
    const isConfirm = await app.$confirm.popup({
      title: "提示",
      content: "确认要删除此校验分组吗？",
      status: "warn",
      okText: "确认"
    });
    if (isConfirm.type == "cancel") return;
    await modelService.removeModel(this.projectId, [this.selectedGroup.instanceId]);
    this.selectedGroup = null;
    this.init();
  }
  handleNodeClick(node: ValidationRuleModelVo) {
    this.selectedNode = node;
  }
  handleClickGroup(item: ValidationModelInstanceVo) {
    this.selectedGroup = item;
    this.loadData();
  }

  async handleShowAttr(node: ValidationRuleModelVo) {
    const model = await modelService.getModelData(this.projectId, node.instanceId);
    await modelDetail.popup({
      projectId: this.projectId,
      modelId: node.instanceId,
      metaclass: model.metaclass!,
      profileRootModelId: "",
      activeKey: ""
    });
    this.init();
  }

  async loadData() {
    const data = await modelService.queryValidationModelsOfValidationGroup({
      projectId: this.projectId,
      validationGroupInstanceId: this.selectedGroup!.instanceId
    });
    treeForEach(data, (node: ValidationRuleModelVo) => {
      node.icon = modelService.getModelIcon(this.projectId, node.icon);
    });
    this.treeData = data;
  }

  // 保存节点名称
  async saveName(data: ValidationModelInstanceVo, newName: string) {
    if (newName && newName.trim() !== "" && data.instanceName !== newName) {
      data.instanceName = newName;
      await modelService.renameNode(this.projectId, data.instanceId, newName).catch(err => console.log(err));
    }
    data.isEdit = false;
  }

  // 取消编辑
  cancelEdit(data: ValidationModelInstanceVo) {
    data.isEdit = false;
  }

  handleRule() {
    if (!this.selectedGroup) {
      return app.$notify({
        title: "提示",
        type: "info",
        message: "请选择校验分组"
      });
    }
    RuleManagerWindow.popup({
      projectId: this.projectId,
      groupId: this.selectedGroup!.instanceId,
      groupName: this.selectedGroup!.instanceName
    }).then(res => {
      if (res.success) {
        app.$notify({
          type: "success",
          title: locale.t("提示"),
          message: locale.t("操作成功")
        });
      }
      this.handleClickGroup(this.selectedGroup!);
    });
  }
}
